<template>
  <div class="booking-calendar">
    <div class="calendar-container">
      <div class="sidebar">
        <!-- 教练选择 -->
        <el-card class="coach-selector">
          <template #header>
            <span>选择教练</span>
          </template>
          <div class="coach-list">
            <div 
              v-for="coach in myCoaches" 
              :key="coach.id"
              class="coach-item"
              :class="{ active: selectedCoachId === coach.id }"
              @click="selectCoach(coach.id)"
            >
              <el-avatar :size="40" :src="coach.avatar">
                {{ coach.name.charAt(0) }}
              </el-avatar>
              <div class="coach-info">
                <div class="coach-name">{{ coach.name }}</div>
                <div class="coach-rate">¥{{ coach.rate }}/小时</div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 预约信息 -->
        <el-card class="booking-info" v-if="selectedTimeSlot">
          <template #header>
            <span>预约信息</span>
          </template>
          <div class="booking-details">
            <p><strong>教练：</strong>{{ getCoachName(selectedCoachId) }}</p>
            <p><strong>日期：</strong>{{ selectedTimeSlot.date }}</p>
            <p><strong>时间：</strong>{{ selectedTimeSlot.time }}</p>
            <p><strong>球台：</strong>{{ selectedTimeSlot.table || '系统分配' }}</p>
            <p><strong>费用：</strong>¥{{ getCoachRate(selectedCoachId) }}</p>
          </div>
          <div class="booking-actions">
            <el-button type="primary" @click="confirmBooking">确认预约</el-button>
            <el-button @click="cancelSelection">取消</el-button>
          </div>
        </el-card>

        <!-- 我的预约 -->
        <el-card class="my-bookings">
          <template #header>
            <span>今日预约</span>
          </template>
          <div class="booking-list">
            <div 
              v-for="booking in todayBookings" 
              :key="booking.id"
              class="booking-item"
            >
              <div class="booking-time">{{ booking.time }}</div>
              <div class="booking-coach">{{ booking.coach }}</div>
              <div class="booking-table">{{ booking.table }}</div>
              <el-tag 
                :type="getStatusTagType(booking.status)" 
                size="small"
              >
                {{ booking.status }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </div>

      <div class="main-content">
        <!-- 日历头部 -->
        <div class="calendar-header">
          <div class="header-left">
            <h2>课表预约</h2>
            <p>选择可用时间段进行预约</p>
          </div>
          <div class="header-right">
            <el-button-group>
              <el-button @click="previousWeek">
                <el-icon><ArrowLeft /></el-icon>
                上周
              </el-button>
              <el-button @click="nextWeek">
                下周
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </el-button-group>
            <span class="current-week">{{ currentWeekRange }}</span>
          </div>
        </div>

        <!-- 时间表格 -->
        <div class="time-table">
          <div class="table-header">
            <div class="time-cell">时间</div>
            <div 
              v-for="day in weekDays" 
              :key="day.date"
              class="day-cell"
              :class="{ today: day.isToday }"
            >
              <div class="day-name">{{ day.name }}</div>
              <div class="day-date">{{ day.date }}</div>
            </div>
          </div>
          
          <div class="table-body">
            <div 
              v-for="time in timeSlots" 
              :key="time"
              class="time-row"
            >
              <div class="time-cell">{{ time }}</div>
              <div 
                v-for="day in weekDays" 
                :key="`${day.date}-${time}`"
                class="slot-cell"
                :class="getSlotClass(day.date, time)"
                @click="selectTimeSlot(day.date, time)"
              >
                <div class="slot-content">
                  {{ getSlotContent(day.date, time) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

// 我的教练数据
const myCoaches = ref([
  { id: '1', name: '李教练', rate: 150, avatar: '' },
  { id: '2', name: '王教练', rate: 200, avatar: '' }
])

// 选中的教练
const selectedCoachId = ref('')

// 选中的时间段
const selectedTimeSlot = ref<any>(null)

// 当前周
const currentWeek = ref(new Date())

// 时间段
const timeSlots = [
  '09:00-10:00',
  '10:00-11:00',
  '11:00-12:00',
  '14:00-15:00',
  '15:00-16:00',
  '16:00-17:00',
  '17:00-18:00',
  '18:00-19:00'
]

// 今日预约
const todayBookings = ref([
  {
    id: '1',
    time: '15:00-16:00',
    coach: '李教练',
    table: '球台1',
    status: '已确认'
  },
  {
    id: '2',
    time: '16:00-17:00',
    coach: '王教练',
    table: '球台2',
    status: '待确认'
  }
])

// 预约数据（模拟）
const bookingData = reactive({
  '2024-01-15': {
    '09:00-10:00': { status: 'booked', coach: '李教练', table: '球台1' },
    '10:00-11:00': { status: 'available' },
    '15:00-16:00': { status: 'booked', coach: '王教练', table: '球台2' }
  },
  '2024-01-16': {
    '09:00-10:00': { status: 'available' },
    '14:00-15:00': { status: 'available' },
    '15:00-16:00': { status: 'booked', coach: '李教练', table: '球台1' }
  }
  // 更多日期数据...
})

// 计算当前周的日期范围
const currentWeekRange = computed(() => {
  const start = getWeekStart(currentWeek.value)
  const end = getWeekEnd(currentWeek.value)
  return `${formatDate(start)} - ${formatDate(end)}`
})

// 计算当前周的日期
const weekDays = computed(() => {
  const start = getWeekStart(currentWeek.value)
  const days = []
  const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(start)
    date.setDate(start.getDate() + i)
    const dateStr = formatDate(date)
    
    days.push({
      name: dayNames[i],
      date: dateStr,
      isToday: dateStr === formatDate(new Date())
    })
  }
  
  return days
})

// 获取周开始日期（周一）
const getWeekStart = (date: Date) => {
  const d = new Date(date)
  const day = d.getDay()
  const diff = d.getDate() - day + (day === 0 ? -6 : 1)
  return new Date(d.setDate(diff))
}

// 获取周结束日期（周日）
const getWeekEnd = (date: Date) => {
  const start = getWeekStart(date)
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  return end
}

// 格式化日期
const formatDate = (date: Date) => {
  return date.toISOString().split('T')[0]
}

// 选择教练
const selectCoach = (coachId: string) => {
  selectedCoachId.value = coachId
  selectedTimeSlot.value = null
}

// 获取教练名称
const getCoachName = (coachId: string) => {
  const coach = myCoaches.value.find(c => c.id === coachId)
  return coach?.name || ''
}

// 获取教练费率
const getCoachRate = (coachId: string) => {
  const coach = myCoaches.value.find(c => c.id === coachId)
  return coach?.rate || 0
}

// 选择时间段
const selectTimeSlot = (date: string, time: string) => {
  if (!selectedCoachId.value) {
    ElMessage.warning('请先选择教练')
    return
  }

  const slotData = bookingData[date]?.[time]
  if (slotData?.status === 'booked') {
    ElMessage.warning('该时间段已被预约')
    return
  }

  selectedTimeSlot.value = {
    date,
    time,
    table: null // 系统分配
  }
}

// 获取时间段样式类
const getSlotClass = (date: string, time: string) => {
  const slotData = bookingData[date]?.[time]
  const classes = ['slot']
  
  if (slotData?.status === 'booked') {
    classes.push('booked')
  } else {
    classes.push('available')
  }
  
  if (selectedTimeSlot.value?.date === date && selectedTimeSlot.value?.time === time) {
    classes.push('selected')
  }
  
  return classes
}

// 获取时间段内容
const getSlotContent = (date: string, time: string) => {
  const slotData = bookingData[date]?.[time]
  
  if (slotData?.status === 'booked') {
    return slotData.coach
  } else {
    return '可预约'
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '已确认': 'success',
    '待确认': 'warning',
    '已取消': 'info'
  }
  return typeMap[status] || 'info'
}

// 确认预约
const confirmBooking = async () => {
  if (!selectedTimeSlot.value || !selectedCoachId.value) {
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要预约 ${getCoachName(selectedCoachId.value)} 的课程吗？\n费用：¥${getCoachRate(selectedCoachId.value)}`,
      '确认预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 这里应该调用API提交预约
    const { date, time } = selectedTimeSlot.value
    
    // 更新预约数据
    if (!bookingData[date]) {
      bookingData[date] = {}
    }
    bookingData[date][time] = {
      status: 'booked',
      coach: getCoachName(selectedCoachId.value),
      table: '球台1'
    }

    ElMessage.success('预约成功，等待教练确认')
    selectedTimeSlot.value = null
  } catch {
    // 用户取消
  }
}

// 取消选择
const cancelSelection = () => {
  selectedTimeSlot.value = null
}

// 上一周
const previousWeek = () => {
  const newDate = new Date(currentWeek.value)
  newDate.setDate(newDate.getDate() - 7)
  currentWeek.value = newDate
}

// 下一周
const nextWeek = () => {
  const newDate = new Date(currentWeek.value)
  newDate.setDate(newDate.getDate() + 7)
  currentWeek.value = newDate
}

onMounted(() => {
  // 默认选择第一个教练
  if (myCoaches.value.length > 0) {
    selectedCoachId.value = myCoaches.value[0].id
  }
})
</script>

<style scoped lang="scss">
.booking-calendar {
  .calendar-container {
    display: flex;
    gap: 20px;
    height: calc(100vh - 120px);

    .sidebar {
      width: 300px;
      display: flex;
      flex-direction: column;
      gap: 16px;

      .coach-selector {
        .coach-list {
          .coach-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;

            &:hover {
              background-color: #f5f7fa;
            }

            &.active {
              background-color: #fff5e6;
              border-color: #ff7700;
            }

            .coach-info {
              flex: 1;

              .coach-name {
                font-weight: 500;
                margin-bottom: 4px;
              }

              .coach-rate {
                font-size: 12px;
                color: #ff7700;
              }
            }
          }
        }
      }

      .booking-info {
        .booking-details {
          p {
            margin: 8px 0;
            font-size: 14px;

            strong {
              color: #333;
            }
          }
        }

        .booking-actions {
          margin-top: 16px;
          display: flex;
          gap: 8px;

          .el-button {
            flex: 1;
          }
        }
      }

      .my-bookings {
        flex: 1;
        overflow: hidden;

        :deep(.el-card__body) {
          height: 100%;
          overflow-y: auto;
        }

        .booking-list {
          .booking-item {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 8px;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
            font-size: 12px;

            &:last-child {
              border-bottom: none;
            }

            .booking-time {
              font-weight: 500;
            }
          }
        }
      }
    }

    .main-content {
      flex: 1;
      display: flex;
      flex-direction: column;

      .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid #e5e7eb;

        .header-left {
          h2 {
            margin: 0 0 4px 0;
            color: #1f2937;
          }

          p {
            margin: 0;
            color: #6b7280;
            font-size: 14px;
          }
        }

        .header-right {
          display: flex;
          align-items: center;
          gap: 16px;

          .current-week {
            font-weight: 500;
            color: #374151;
          }
        }
      }

      .time-table {
        flex: 1;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        overflow: hidden;

        .table-header {
          display: grid;
          grid-template-columns: 120px repeat(7, 1fr);
          background-color: #f9fafb;
          border-bottom: 1px solid #e5e7eb;

          .time-cell, .day-cell {
            padding: 12px;
            text-align: center;
            font-weight: 600;
            border-right: 1px solid #e5e7eb;

            &:last-child {
              border-right: none;
            }
          }

          .day-cell {
            &.today {
              background-color: #fff5e6;
              color: #ff7700;
            }

            .day-name {
              margin-bottom: 4px;
            }

            .day-date {
              font-size: 12px;
              font-weight: normal;
            }
          }
        }

        .table-body {
          .time-row {
            display: grid;
            grid-template-columns: 120px repeat(7, 1fr);
            border-bottom: 1px solid #f0f0f0;

            &:last-child {
              border-bottom: none;
            }

            .time-cell {
              padding: 16px 12px;
              text-align: center;
              font-weight: 500;
              background-color: #f9fafb;
              border-right: 1px solid #e5e7eb;
            }

            .slot-cell {
              padding: 16px 8px;
              text-align: center;
              border-right: 1px solid #f0f0f0;
              cursor: pointer;
              transition: all 0.2s;

              &:last-child {
                border-right: none;
              }

              &.available {
                background-color: #f0f8f0;
                color: #16a34a;

                &:hover {
                  background-color: #dcfce7;
                }
              }

              &.booked {
                background-color: #fef2f2;
                color: #dc2626;
                cursor: not-allowed;
              }

              &.selected {
                background-color: #ff7700;
                color: white;
              }

              .slot-content {
                font-size: 12px;
                font-weight: 500;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .calendar-container {
    flex-direction: column;
    height: auto;

    .sidebar {
      width: 100%;
      flex-direction: row;
      overflow-x: auto;

      .coach-selector,
      .booking-info,
      .my-bookings {
        min-width: 250px;
      }
    }

    .time-table {
      .table-header,
      .time-row {
        grid-template-columns: 80px repeat(7, minmax(80px, 1fr));
      }
    }
  }
}
</style>
